Home:ALL Converter>Web Audio API - How to set gain of output but also specify the channel to output to?

Web Audio API - How to set gain of output but also specify the channel to output to?

Ask Time:2018-11-15T22:01:07         Author:Luke Ireton

Json Formatter

My code:

// Create an AudioContext instance for this sound
    var audioContext = new (window.AudioContext || window.webkitAudioContext)();
    var maxChannelCount = audioContext.destination.maxChannelCount;
    var gainNode = audioContext.createGain()
    audioContext.destination.channelCount = maxChannelCount;

    var merger = audioContext.createChannelMerger(maxChannelCount);
    merger.connect(audioContext.destination);

    gainNode.gain.value = 0.1 // 10 %
    gainNode.connect(audioContext.destination)
    // Create a buffer for the incoming sound content
    var source = audioContext.createBufferSource();

    // Create the XHR which will grab the audio contents
    var request = new XMLHttpRequest();
    // Set the audio file src here
    request.open('GET', 'phonemes/bad-bouyed/bad.mp3', true);
    // Setting the responseType to arraybuffer sets up the audio decoding
    request.responseType = 'arraybuffer';
    request.onload = function() {
      // Decode the audio once the require is complete
      audioContext.decodeAudioData(request.response, function(buffer) {
        source.buffer = buffer;


        // Connect the audio to source (Can I also set the gain within this declaration?)
        source.connect(merger, 0,10);


        // Simple setting for the buffer
        source.loop = false;
        // Play the sound!
        source.start(0);
      }, function(e) {
        console.log('Audio error! ', e);
      });
    }
    // Send the request which kicks off
    request.send();

The above code loads an mp3 file in and plays it using Web Audio API, this works great although I am just wondering if it is possible to set the gain of the source AND also set the output channel using my already existing code. You can see above I have already created a gain node and connected the audio context. What is the syntax for specifying both? Do I declare them in the order I wish for them to be executed?

For example

source.connect(merger, 0,10);

source.connect(gainNode);

Any help on this would be great.

Author:Luke Ireton,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53321148/web-audio-api-how-to-set-gain-of-output-but-also-specify-the-channel-to-output
yy